// pages/package/coupon/myCoupon.js
var app = getApp()
Page({
  data: {
    topBar:'0',
    accountId:'',
    couponList:[],
    count0:'',count1:'',count2:''
  },
  onLoad: function (options) {
    app.getMemInfo().then(res=>{
      console.log()
      this.setData({
        accountId:res.data.id
      })
      this.getCoupon(0)
      for (var i = 0; i < 3; i++) {
        this.getCouponCount(i)
      }
    })
  },
  topSelect(e){
    let type = e.currentTarget.dataset.type
    this.setData({
      topBar:type
    })
    if (type==0) {
      this.getCoupon(type)
    }else if (type==1) {
      this.getCoupon(type)
    }else{
      this.getCoupon(type)
    }
  },
  getCoupon(isUse){
    wx.showLoading({
      title: '加载中',
    })
    let data = {
      accountId:this.data.accountId,
      isUse
    }
    app.request('wx_app/coupon/getCouponsByAccountIdAndIsUse',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        res.data.forEach(item=>{
          item.start = item.begin_time.split('T')[0]
          item.end = item.end_time.split('T')[0]
        })
        wx.hideLoading()
        this.setData({
          couponList:res.data
        })
      }else{
        wx.hideLoading()
        app.errorMsg(res.message)
      }
    })
  },
  getCouponCount(isUse){
    wx.showLoading({
      title: '加载中',
    })
    let data = {
      accountId:this.data.accountId,
      isUse
    }
    app.request('wx_app/coupon/getCouponsByAccountIdAndIsUse',data,'GET').then(res=>{
      if(res.code==1){
        this.setData({
          ['count'+isUse+'']:res.data.length
        })
      }else{
        app.errorMsg(res.message)
      }
    })
  },
  delCoupon(e){
    wx.showLoading({
      title: '删除中',
    })
    let crId = e.currentTarget.dataset.id
    let data = {
      accountId:this.data.accountId,
      crId
    }
    app.request('wx_app/coupon/del',data,'GET').then(res=>{
      console.log(res)
      if (res.code==1) {
        wx.hideLoading()
        this.getCoupon(this.data.topBar)
        for (var i = 0; i < 3; i++) {
          this.getCouponCount(i)
        }
        app.errorMsg('删除成功')
      }else{
        wx.hideLoading()
        app.errorMsg(res.message)
      }
    })
  }
})